package org.edu.common.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.edu.model.User;
/**
 * url 过滤类 尚未完成
 * @author lenove-x
 *
 */
public class AdminFilter implements Filter {
	protected FilterConfig ftConfig;
	protected String ignoreURL = null;
	protected List<String> alIgnoreURL = new ArrayList<String>();

	public void destroy() {
	

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		HttpSession session=req.getSession();
		//System.out.println(alIgnoreURL);
		String toPage = req.getSession().getServletContext().getContextPath();//+"/index.jsp";
		
		String requestUrl = req.getRequestURI();//获取访问的url
		//System.out.println(requestUrl);
		
		if (!isIgnoreURL(requestUrl, req.getContextPath() + java.io.File.pathSeparator)){
			User u=(User)session.getAttribute("user");
			
//			@SuppressWarnings("unchecked")
//			List<User> l= (List<User>)session.getServletContext().getAttribute("allusers");//在线用户数
//			System.out.println("在线用户数list.size():"+l.size());
			if(null!=u){
				
				if(!"4028b8814bb53e6f014bb53e73dd0000".equals(u.getRoleid().getId())){
					toPage+="/Interface/hello.jsp";
					resp.sendRedirect(toPage);
				}
			}else{
				toPage+="/index.jsp";
				resp.sendRedirect(toPage);
			}
		}
		chain.doFilter(req, resp);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.ftConfig = filterConfig;
		this.ignoreURL = ftConfig.getInitParameter("ignoreURL");
		StringTokenizer tokenizer = new StringTokenizer(ignoreURL, ",");
		//按照','来分割字符串
		while (tokenizer.hasMoreElements()) {
			alIgnoreURL.add(tokenizer.nextElement().toString());
		}
	}
	
	public boolean isIgnoreURL(String url, String contextPath) {
		for (int i = 0; i < this.alIgnoreURL.size(); i++) {
			if (url.indexOf(this.alIgnoreURL.get(i)) != -1) {
				return false;
			}
			if (url.equals(contextPath + "/")) {
				return false;
			}
		}
		return true;
	}

}
